package com.example.recyclerviewtest.adapter;

import android.annotation.SuppressLint;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.recyclerviewtest.R;
import com.example.recyclerviewtest.bean.NewsBean;

import java.util.List;
import java.util.Random;

public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.MyViewHolder> {


    private List<NewsBean> beanList;
    private LayoutInflater layoutInflater;
    private Context context;

    public RecyclerAdapter(List<NewsBean> beanList, Context context) {
        this.beanList = beanList;
        this.context = context;
        layoutInflater=LayoutInflater.from(context);
    }



    @NonNull
    @Override
    public RecyclerAdapter.MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = View.inflate(context,R.layout.list_item_layout,null);

        return new MyViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerAdapter.MyViewHolder holder, @SuppressLint("RecyclerView") int position) {
        NewsBean bean = beanList.get(position);
        holder.tv_title.setText(bean.getTitle());
        holder.tv_content.setText(bean.getContent());
        holder.iv_img.setImageResource(bean.getImageResourceId());

        Random random=new Random();
        int number = random.nextInt(40) - 10;

        holder.iv_img.setLayoutParams(new RelativeLayout.LayoutParams(dpTodx(100),dpTodx(100+number)));

        holder.relativeLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(context,"您点击了"+position+"个",Toast.LENGTH_SHORT).show();
            }
        });
    }

    private int dpTodx(int dp){
        final float scale=context.getResources().getDisplayMetrics().density;
        return (int)(dp*scale+0.5f);
    }

    @Override
    public int getItemCount() {
        if (beanList.isEmpty()){
            return 0;
        }
        return beanList.size();
    }

    public static class MyViewHolder extends RecyclerView.ViewHolder {
        TextView tv_title;
        TextView tv_content;
        ImageView iv_img;
        RelativeLayout relativeLayout;


        public MyViewHolder(@NonNull View itemView) {
            super(itemView);
            tv_title=itemView.findViewById(R.id.tv_title);
            tv_content=itemView.findViewById(R.id.tv_content);
            iv_img=itemView.findViewById(R.id.iv_img);
            relativeLayout=itemView.findViewById(R.id.rl_container);
        }
    }
}
